package com.surfilter.util;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yeyonghuan Mar 27, 2009,4:32:09 PM
 */
public class StringUtil {
	private static final String TRIM_REGEX = "^[?? ]+|[?? ]+$";
	public static final String BLANK = "";

	public static final String BLANK2 = "|";

	public static final String BACKLASH = "/";

	static final String HEX_REFERENCE_START = "&#x";

	static final char REFERENCE_END = ';';

	/**
	 * �ո�
	 */
	private static final String SPACE_STR = "&nbsp;";

	/**
	 * oracle sql contains ����??Ҫ���������ַ�and , or , ADN , OR
	 * ,--,&,|,(,),[,],',",~~,*,{,},<,>,!,=,%
	 */
	private static final String SQL_SAVE_REGEX = "(\\s+and+\\s)+|(\\s+or+\\s)"
			+ "+|(\\s+AND+\\s)+|(\\s+OR+\\s)+|(--)+|[\\&]"
			+ "+|[\\(]+|[\\)]+|[\\\"]+|[\\\']"
			+ "+|[\\[]+|[\\]]+|(~~)+|[\\*]+|[\\{]+|[\\}]+|[\\<]+|[\\>]+|[\\!]+|[\\=]+|[\\%]";

	/**
	 * ȥȫ�ǺͰ�ǿո�
	 * 
	 * @param str
	 * @return
	 */
	public static String trim(String str) {
		if (str == null || str.equals(BLANK)) {
			return str;
		} else {
			return str.replaceAll(TRIM_REGEX, BLANK);
		}
	}

	/**
	 * ����ĸ��д���紫��id���õ�Id
	 * 
	 * @param fieldName
	 * @return
	 * @throws Exception
	 */
	public static String firstUpperCase(String fieldName) {
		return fieldName == null || trim(fieldName).length() == 0

		? fieldName

		: fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

	}

	/**
	 * ���ַ�ת����utf-8��ʽ wenjianping 2009-09-16
	 * 
	 * @param str
	 *            �ַ�??
	 * 
	 * 
	 * 
	 * @return ת������ַ�??
	 * 
	 * 
	 * 
	 */
	public static String toUtf8String(String str) {
		StringBuffer stringBuffer = new StringBuffer();

		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i); // NOPMD
			if (c >= 0 && c <= 255) {
				stringBuffer.append(c);
			} else {
				byte[] bytes;
				try {
					bytes = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					
					bytes = new byte[0]; // NOPMD
				}
				for (int j = 0; j < bytes.length; j++) {
					int k = bytes[j]; // NOPMD
					if (k < 0) {
						k += 256;
					}

					stringBuffer.append('%').append(
							Integer.toHexString(k).toUpperCase(
									Locale.getDefault()));
				}
			}
		}
		return stringBuffer.toString();
	}

	/**
	 * �ַ�ת����16���Ʊ���
	 * 
	 * @param input
	 * @return
	 */
	public static String stringEscapeHex(String input) {
		if (input == null) {
			return null;
		}
		StringBuffer escaped = new StringBuffer(input.length() * 2);
		for (int i = 0; i < input.length(); i++) {
			char character = input.charAt(i);

			escaped.append(HEX_REFERENCE_START);
			escaped.append(Integer.toString((int) character, 16));
			escaped.append(REFERENCE_END);
		}
		return escaped.toString();
	}

	/**
	 * ������ת���Զ��ŷָ���ַ�
	 * 
	 * @param ids
	 * @return
	 */
	public static String intsToString(int[] ids) {
		StringBuilder sb = new StringBuilder();
		int i = 0;
		for (int j : ids) {
			if (i > 0) {
				sb.append(",");
			}
			sb.append(j);
			i++;
		}
		return sb.toString();
	}

	/**
	 * listת����string
	 * 
	 * @param list
	 * @return
	 */
	public static String listToString(List list) {
		Object[] toBeStored = list.toArray();
		StringBuffer sb = new StringBuffer("");
		for (Object s : toBeStored) {
			sb.append("#");
			sb.append(s);
		}
		return sb.toString().replaceFirst("#", "");
	}

	/**
	 * oracle contains�����������ַ�
	 * 
	 * @param str
	 * @return
	 */
	public static String safeSQL(String str) {
		if (str != null) {
			return trim(str).replaceAll(SQL_SAVE_REGEX, BLANK2);
		}
		return str;
	}

	public static String formatURL(String str) {
		if (str != null) {
			if (trim(str).endsWith(BACKLASH)) {
				return trim(str).substring(0, trim(str).lastIndexOf(BACKLASH));
			}
			return trim(str);
		}
		return str;
	}

	/**
	 * ��һ��urlת���ɰ������ӵ�html���� ʾ��[http://www.163.com]
	 * 
	 * @param txt
	 *            ����
	 * @return ���صĴ�??
	 * 
	 * 
	 * 
	 */
	public static String convertLinkText(String txt) {
		StringBuffer str = new StringBuffer();
		char[] tmp = txt.toCharArray();
		for (int i = 0; i < tmp.length; i++) {
			if (tmp[i] == '[' && (i + 7) < tmp.length
					&& txt.substring(i + 1, i + 8).equalsIgnoreCase("http://")) {
				int lastFlagIndex = txt.indexOf(']', i + 1);
				if (lastFlagIndex == -1) {
					str.append(tmp[i]);
					continue;
				} else {
					String url = txt.substring(i + 1, lastFlagIndex);
					url = url.replaceAll("<", "&lt;");
					url = url.replaceAll(">", "&gt;");
					str.append("<a href=").append(url)
							.append(" target=_blank>").append(url).append(
									"</a>");
					i = lastFlagIndex;
					continue;
				}

			} else {
				str.append(StringUtil.encodeHTML(String.valueOf(tmp[i])));
			}
		}

		return str.toString();
	}

	/**
	 * ���ַ���˵�HTML��ǩ �����ҳ����ʾ�ı���ݣ�����˵�����������ݣ���???�Ҹö����
	 * ���Ƿ���ҳ���textarea����ʾʱ������ʹ�ø÷������˵�html��includeftl��ǩ
	 * 
	 * @param str
	 *            �ַ�??
	 * 
	 * 
	 * 
	 * @return ת������ַ�??
	 * 
	 * 
	 * 
	 */
	public static String encodeHTML(String str) {
		// ��ʱ����
		String tempStr = str;

		if (tempStr == null || tempStr.length() == 0) {
			return "";
		}
		// ��ǰ??&ת�������򣬺���ת���󣬾ͻ��ڰ�ת�����&��ת��һ??

		tempStr = tempStr.replaceAll("&", "&amp;");

		tempStr = tempStr.replaceAll("<", "&lt;");
		tempStr = tempStr.replaceAll(">", "&gt;");
		tempStr = tempStr.replaceAll("\'", "&acute;");
		tempStr = tempStr.replaceAll(String.valueOf((char) 32),
				StringUtil.SPACE_STR);
		tempStr = tempStr.replaceAll(String.valueOf((char) 9),
				StringUtil.SPACE_STR);
		tempStr = tempStr.replaceAll(String.valueOf((char) 34), "&quot;");
		tempStr = tempStr.replaceAll(String.valueOf((char) 39), "&#39;");
		tempStr = tempStr.replaceAll(String.valueOf((char) 13), "");
		tempStr = tempStr.replaceAll(String.valueOf((char) 10), "<BR> ");
		tempStr = tempStr.replaceAll(String.valueOf(new char[] { (char) 10,
				(char) 10 }), "</P><P> ");

		return tempStr;
	}

	/**
	 * ȥ���ַ�ǰ��ȫ??0
	 */
	public static String filerZero(String str) {
		String result = "";
		String newStr = trim(str);
		int index = 0;
		for (int i = 0; i < newStr.length(); i++) {
			if (newStr.charAt(i) != '0') {
				index = i;
				break;
			}
		}
		result = newStr.substring(index);
		return result;
	}

	/**
	 * ��ݿ����������ֽ���������ݿ��д洢����ݵĺͽ�����2��N�η������鷵��???
	 * 
	 * @param number
	 * @return
	 */
	public static List<Long> dataForShow(Long number) {
		DecimalFormat df = new DecimalFormat("0.00");
		String str = StringUtil.convertNumber(number);
		char[] ch = str.toCharArray();
		List<Long> nu = new ArrayList<Long>();
		for (int i = 0; i < ch.length; i++) {
			int j = ch.length - 1 - i;
			if (ch[i] == '1') {
				Double a = Math.pow((double) 2, (double) j);
				try {
					nu.add(Long.parseLong(df.format(a).substring(0,
							df.format(a).indexOf("."))));
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}

			}
		}
		return nu;
	}

	/**
	 * ���ַ�ת��?? int.
	 * 
	 * @param input
	 *            �������?? *
	 * @return �������
	 */
	public static int parseInt(String input) {
		try {
			return Integer.parseInt(input);
		} catch (Exception e) {
		}
		return 0;
	}

	/**
	 * ���ַ�ת��?? long.
	 * 
	 * @param input
	 *            �������??
	 * @return �������
	 */
	public static long parseLong(String input) {
		try {
			return Long.parseLong(input);
		} catch (Exception e) {
		}
		return 0;
	}

	/**
	 * ���ַ�ת��?? long.
	 * 
	 * @param input
	 *            �������??
	 * @return �������
	 */
	public static double parseDouble(String input) {
		try {
			return Double.parseDouble(input);
		} catch (Exception e) {
		}
		return 0;
	}

	/**
	 * �Կ��ַ�NULLֵ�Ĵ���
	 * 
	 * @param obj
	 *            ??Ҫ����Ķ���
	 * @return String ������ַ�
	 */
	public static String toString(Object obj) {
		String str = String.valueOf(obj);
		if (str == null || str.equals("") || str.equals("null")) {
			return "";
		} else {
			return str;
		}

	}

	/**
	 * ������ֻ�ȡ��Ӧ�Ĵ�дӢ����??
	 * 
	 * @param t
	 *            ����
	 * @return ��Ӧ�Ĵ�дӢ����??
	 */

	public static String getEnglishWordByNumber(int t) {
		int i = 65 + t;
		char tt = (char) i;
		return String.valueOf(tt);
	}

	/**
	 * �ж�Դ�ֶδ����Ƿ��Ŀ���ֶδ�
	 * 
	 * @param src
	 *            Դ�ַ�
	 * @param tar
	 *            Ŀ���ַ�??
	 * @return
	 */
	public static boolean contains(String src, String tar) {
		if (src == null || tar == null) {
			return false;
		}
		return src.indexOf(tar) == -1 ? false : true;
	}

	/**
	 * �ж��ַ��Ƿ�Ϊ??
	 * 
	 * @param string
	 *            �����ַ�??
	 * @return boolean �����Ƿ�Ϊ�� ��true?? �գ�false��Ϊ??)
	 */
	public static boolean isEmpty(String string) {
		return string == null || string.length() == 0;
	}

	/**
	 * ��ȡ��ˮ??,????18??
	 * 
	 * @return
	 */
	public static Long getFlowNumber() {
		// Random random = new Random(System.currentTimeMillis());
		// Long k = random.nextLong();
		//
		// /**
		// * ȡһ�������ɵ���???��Ϊβ������ظ���ˮ??
		// */
		// if (k >= 100) {
		// k = k % 100;
		// }

		SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// // Long j = Math.abs(k % 1000000000);
		// log.info(newFormat.format(new Date()) + j);

		// log.info(newFormat.format(new Date()));
		return Long.parseLong(newFormat.format(new Date()));

	}

	/**
	 * 
	 * ������ת�����ֽ�
	 * 
	 * @param number
	 * @return
	 */
	public static String convertNumber(Long number) {
		return Long.toBinaryString(number);
	}

	/**
	 * ���ַ������ۼ� �ַ��ʽΪ 1#2#3#4
	 * 
	 * @param nrlxAddId
	 * @return
	 */
	public static Long sum(String nrlxAddId) {
		Long sum = 0L;
		if (nrlxAddId == null) {
			return 0L;
		}
		String[] strs = nrlxAddId.split("#");

		for (String str : strs) {
			sum = sum + Long.valueOf(str);
		}

		return sum;
	}

	/**
	 * �滻�ַ��??��xxΪ��
	 * 
	 * @param str
	 *            ??Ҫ�滻���ַ�??
	 * @param xx
	 *            ��ʶ??
	 * @return String ��������ַ�??
	 */
	public static String replaceFirst(String str, String xx) {
		if (str != null && !str.equals("") && !str.equals("null")
				&& str.startsWith(xx)) {
			str = str.replaceFirst(xx, "");
		}
		return str;
	}

	/**
	 * 
	 * 
	 * @name ��ʱ��ȡ���??
	 * @Description ���˵��
	 * @Time ����ʱ��:Apr 13, 20105:40:31 PM
	 * @return
	 * @history �޶���ʷ������޶�����???�޶��ˡ��޶�ʱ���??
	 */
	public static String getRandom() {
		int[] intRet = new int[6];
		int intRd = 0; // ������??
		int count = 0; // ��¼��ɵ���������
		int flag = 0; // �Ƿ��Ѿ���ɹ��??
		while (count < 6) {
			Random rdm = new Random(System.currentTimeMillis());
			intRd = Math.abs(rdm.nextInt()) % 32 + 1;
			for (int i = 0; i < count; i++) {
				if (intRet[i] == intRd) {
					flag = 1;
					break;
				} else {
					flag = 0;
				}
			}
			if (flag == 0) {
				intRet[count] = intRd;
				count++;
			}
		}
		return String.valueOf(intRet[0]);
	}
	/**
	 * String null
	 * @param object
	 * @param string
	 * @return
	 */
	public static String nullObjectFormat(Object object, String string) {
		String str;
		if (object == null) {
			str = string;
		} else if (object.equals("null")) {
			str = string;
		} else {
			str = object.toString();
		}
		return str;
	}
	
	public static Long match(String ip){
		String[] ips=ip.split("\\.");
		String ss="";
		for(int i=0;i<ips.length;i++){
			if(ips[i].length()<=3){
				for(int j=0;j<3-ips[i].length();j++){
					ss+="0";
				}
			}
			ss+=ips[i];
		}
		return Long.parseLong(ss);
	}
	
	public static boolean isIP(String domain) {
		String pattern = "^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$";
		Matcher matcher = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE).matcher(domain);
		boolean isIP = matcher.find();
		return isIP;
    }
	
	public static String deepUrl(String url) {
		Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
		Matcher m = p.matcher(url);
		String domain = null;
		if(m.find()) {
			domain = m.group();
		}
		return domain;
	}
}
